<template>
    <el-card shadow="hover" :body-style="{ padding: '20px' }">
        <el-button type="primary" size="default" :icon="Plus" @click="addButton" v-if="userInfoStore.buttonsList.includes('btn.Trademark.add')">添加</el-button>
        <el-table border style="margin:10px 0px" :data="tmObj.records" v-loading="loading"
            element-loading-text="努力加载中..." element-loading-background="rgba(122, 122, 122, 0.2)">
            <el-table-column label="序号" width="80px" align="center" type="index"></el-table-column>
            <el-table-column label="商品名称" prop="tmName"></el-table-column>
            <el-table-column label="商品LOGO">
                <template v-slot="{row,$index}">
                    <a>
                        <img :src="row.logoUrl" alt="" style="width: 100px; height: 60px; border-radius: 10px">
                    </a>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #="{row,$index}">
                    <el-button type="warning" size="small" :icon="Edit" @click="change(row)"></el-button>
                    <el-popconfirm :title="`你确定删除${row.tmName}?`" width="250px" :icon="Delete" @confirm="handler(row)">
                        <template #reference>
                            <el-button type="danger" size="small" :icon="Delete"></el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 
       v-model:current-page:决定分页器当前第几页
       v-model:page-size,展示几条数据
       total:设置分页总共数据条数
       page-sizes:设置下拉框里面选择数据的条数
       pager-count:可以设置分页器能看见按钮总个数
       current-change:当前页码发生变化的事件回调
       size-change:当选择每一页展示几个数据的时候(下拉框)发生变化的时候会触发
    -->
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3,5,7]"
            layout="prev, pager, next, jumper,->,sizes,total" :total="tmObj.total" background :pager-count="5"
            @current-change="getTradeMarkList" @size-change="sizeChange">
        </el-pagination>


        <el-dialog v-model="dialogFormVisible" title="添加" draggable>
            <el-form style="width:80%" :model="tmParams" :rules="rules" ref="ruleFormRef">
                <el-form-item label="名称" prop="tmName">
                    <el-input autocomplete="off" v-model="tmParams.tmName" />
                </el-form-item>
                <el-form-item label="LOGO" prop="logoUrl">
                    <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="tmParams.logoUrl" :src="tmParams.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="okButton">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup lang="ts">
//引入element-plus提供icon图标组件
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
    Plus,
} from "@element-plus/icons-vue";
import type { UploadProps, FormRules, FormInstance } from 'element-plus'
import { ElMessage, ElNotification } from 'element-plus'
import { reqAddOrUpdateTradeMark, reqTradeMarkList,reqDeleteTradeMark } from '../../../api/product/trademark/trademark'
import { ref, onMounted, reactive, nextTick } from "vue";
import type { trademark, trademarkResponseData } from '../../../api/product/trademark/model/trademark'
//定义接受服务器返回的狗东西数据:total|records
let tmObj = reactive<trademarkResponseData>({
    total: 0,
    records: [],
});
let tmParams = reactive<trademark>({
    tmName: "",
    logoUrl: ""
})
//存储组件实例el-form
let ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    tmName: [
        { required: true, message: 'Please input Activity name', trigger: 'blur' },
        { min: 3, max: 30, message: 'Length should be 3 to 30', trigger: 'blur' },
    ],
    logoUrl: [{ required: true, message: "要上传图片" }],
})
const dialogFormVisible = ref<boolean>(false)
let loading = ref<boolean>(false)
//保存分页器当前页码[当前第几页]
let currentPage = ref<number>(1);
//保存当前页面显示几条数据
let pageSize = ref<number>(3);
onMounted(() => {
    getTradeMarkList();

})

const getTradeMarkList = async (page: number = 1) => {
    loading.value = true;
    currentPage.value = page
    let reasult = await reqTradeMarkList(currentPage.value, pageSize.value)
    console.log(reasult);
    tmObj.total = reasult.total
    tmObj.records = reasult.records
    loading.value = false;
}
const sizeChange = async (limit: number) => {
    pageSize.value = limit
    getTradeMarkList();
}



const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log(response, uploadFile);
    tmParams.logoUrl = response.data
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    console.log(rawFile);
    if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/webp' || rawFile.type == 'image/gif') {
        if (rawFile.size / 1024 / 1024 < 50) {
            return true
        }
    } else {
        return false
    }
}

const okButton = async () => {
    ruleFormRef.value?.validate(async (success) => {
        if (success) {
            for (let i = 0; i < 2; i++) {
                await reqAddOrUpdateTradeMark(tmParams)
            }
            dialogFormVisible.value = false
            getTradeMarkList(tmParams.id ? currentPage.value : 1);
        } else {
            ElNotification({
                type: "warning",
                message: "大哥你看点规则,别瞎搞",
                duration: 500//提示消息时间的设置
            });
        }
    })

}
const addButton = () => {
    tmParams.id = ''
    tmParams.logoUrl = ''
    tmParams.tmName = ''
    dialogFormVisible.value = true
    //nextTick:当响应式数据发生变化[页面重新渲染],获取更新后的DOM
    nextTick(() => {
        ruleFormRef.value.resetFields();
    })
}
const change = (value: trademark) => {
    console.log(value);
    dialogFormVisible.value = true
    nextTick(() => {
        //重置初始化，再次重新赋值
        //重置该表单项，将其值重置为初始值，并移除校验结果
        ruleFormRef.value.resetFields();
        tmParams.id = value.id
        tmParams.logoUrl = value.logoUrl
        tmParams.tmName = value.tmName
    });


}

//删除某一个数据
const handler = async (row: trademark) => {
    try {
        //删除成功
        await reqDeleteTradeMark(row.id);
        //提示信息
        ElMessage({
            type: "success",
            message: `删除${row.tmName}成功`,
        });
        //再次获取最新数据
        getTradeMarkList(currentPage.value);
    } catch (error) { }
};
</script>


<style scoped>
/**上传照片的样式**/
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
    
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>